package com.woniu.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.user.pojo.TUserWhite;
import com.woniu.user.service.TUserWhiteService;
import com.woniu.user.mapper.TUserWhiteMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author 91211
* @description 针对表【t_user_white(白名单)】的数据库操作Service实现
* @createDate 2024-05-19 14:34:07
*/
@Service
public class TUserWhiteServiceImpl extends ServiceImpl<TUserWhiteMapper, TUserWhite>
    implements TUserWhiteService{

    @Autowired
    private StringRedisTemplate redisTemplate;

    public final static String WHITE = "white";

    @Override
    public String initWhite() {
        //删除白名单缓存数据
        redisTemplate.delete(WHITE);

        //查询mysql白名单所有数据
        List<TUserWhite> list = list();
        //语法糖
        for (TUserWhite financeWhite : list) {
            //大KEY = white 小KYE = PATH value = 中文名称
            redisTemplate.opsForHash().put(WHITE,financeWhite.getPath(),financeWhite.getRouteType());
        }

        return "白名单初始化成功!";
    }

    @Override
    @SneakyThrows
    public String addWhite(String path, String routeType) {
        //先删除
        redisTemplate.opsForHash().delete(WHITE,path);

        //保存到mysql
        TUserWhite white = new TUserWhite();
        white.setPath(path);
        white.setRouteType(routeType);
        save(white);

        //再延时
        Thread.sleep(500);

        //再删除缓存数据
        redisTemplate.opsForHash().delete(WHITE,path);

        //数据保存到缓存中
        redisTemplate.opsForHash().put(WHITE,path,routeType);

        return "增加白名单成功!";
    }

    @Override
    @SneakyThrows
    public String updateWhite(TUserWhite white) {
        //数据一致性,延迟双删 单删
        //white:有那些东西?ID不变,path(修改的值),routeType(修改的值)
        //在修改白名单的时候,修改的字段值可能是path,那么传值过来的path在缓存中不存在,所以我们需要拿ID,查询数据库中原有的path值
        TUserWhite oldWhite = getById(white.getId());

        //先删除缓存数据
        redisTemplate.opsForHash().delete(WHITE,oldWhite.getPath());

        //修改数据到mysql
        updateById(white);

        //再延时
        Thread.sleep(500);

        //再清除缓存数据
        redisTemplate.opsForHash().delete(WHITE,oldWhite.getPath());
        redisTemplate.opsForHash().delete(WHITE,white.getPath());

        //数据保存到缓存中
        redisTemplate.opsForHash().put(WHITE,white.getPath(),white.getRouteType());

        return "修改白名单成功!";
    }
}




